#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <unistd.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>
#include "Log.hpp"

class Sock
{
public:
    Sock() {}

    int Socket()
    {
        int socketFd = socket(AF_INET, SOCK_STREAM, 0);
        if (socketFd < 0)
        {
            logMsg(FATAL, "create socket error, %d:%s", errno, strerror(errno));
            exit(2);
        }
        logMsg(NORMAL, "create socket success, listenSocket: %d", socketFd);
        return socketFd;
    }

    void Bind(int socket, uint16_t port, std::string ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(port);

        if (bind(socket, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMsg(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(3);
        }
    }

    void Listen(int socket)
    {
        if (listen(socket, g_backlog) < 0)
        {
            logMsg(FATAL, "listen error, %d:%s", errno, strerror(errno));
            exit(4);
        }
        logMsg(NORMAL, "listen success");
    }

    // const std::string&: 输入型参数
    // std::string*: 输出型参数
    // std::string&: 输入输出型参数
    //服务端接受客户端发来的连接请求 并 把来源客户端的信息存入对应字段
    int Accept(int listenSocket, std::string *clientIp, uint16_t *clientPort)
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);

        int serviceSocket = accept(listenSocket, (struct sockaddr *)&src, &len);
        if (serviceSocket < 0)
        {
            logMsg(ERROR, "accept error, %d:%s", errno, strerror(errno));
            return -1;
        }

        if (clientPort != nullptr)
            *clientPort = ntohs(src.sin_port);
        if (clientIp != nullptr)
            *clientIp = inet_ntoa(src.sin_addr);

        return serviceSocket;
    }

    //客户端向服务端发起连接请求
    bool Connect(int socketFd, const std::string &serverIp, const uint16_t &serverPort)
    {
        struct sockaddr_in svr_sockAddr;
        memset(&svr_sockAddr, 0, sizeof(svr_sockAddr));
        svr_sockAddr.sin_family = AF_INET;
        svr_sockAddr.sin_addr.s_addr = inet_addr(serverIp.c_str());
        svr_sockAddr.sin_port = htons(serverPort);

        if (connect(socketFd, (struct sockaddr *)&svr_sockAddr, sizeof(svr_sockAddr)) == 0)
            return true;
        else
            return false;
    }

    ~Sock() {}

private:
    static const int g_backlog = 20;
};
